package com.sgb.kjwl.view.ui.activity.transport;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.util.Pair;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.google.gson.JsonObject;
import com.sgb.capital.callback.Constants;
import com.sgb.capital.callback.ZMessageEvent;
import com.sgb.capital.model.PayInfoEntity;
import com.sgb.capital.view.ui.activity.PersonPayActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.UrlConfig;
import com.sgb.kjwl.databinding.ActivityGroupPayGoodsOrderBinding;
import com.sgb.kjwl.model.entity.CarInfo;
import com.sgb.kjwl.model.entity.GoodsOrderEntity;
import com.sgb.kjwl.model.entity.self.GoodsSourceDetail;
import com.sgb.kjwl.model.entity.transport.CompanyGoodsOrderEntity;
import com.sgb.kjwl.model.entity.transport.CompanyInvoiceEntity;
import com.sgb.kjwl.model.entity.transport.SingleItemEntity;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.CargoConstant;
import com.sgb.kjwl.utils.DefaultUtil;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.view.constant.RouterKey;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.event.WebEvent;
import com.sgb.kjwl.view.ui.activity.WebActivity;
import com.sgb.kjwl.view.ui.activity.self.AddCarInfoActivity;
import com.sgb.kjwl.view.ui.activity.transport.owner.TransportOrderDetailOwnerActivity;
import com.sgb.kjwl.view.ui.adapter.transport.CargoCustomValueAdapter;
import com.sgb.kjwl.view.widget.CarListPopWindow;
import com.sgb.kjwl.view.widget.InvoicingCompanyPopWindow;
import com.sgb.kjwl.view.widget.MixCarListPopWindow;
import com.sgb.kjwl.view.widget.transport.AMapDialog;
import com.sgb.kjwl.viewmodel.transport.GroupPayGoodsViewModel;
import com.sgb.link.entity.AMapAddressEntity;
import com.sgb.link.entity.UserInfo;
import com.sgb.link.router.PathLogistics;
import com.swgk.core.base.model.entity.RequestCode;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.event.EventConstant;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.UiUtil;
import com.swgk.core.util.UserOperating;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author: 王彬臣
 * @date: 2022/1/7
 * @Description: 企业/团队普通货源接单
 */
@Route(path = PathLogistics.GroupPayGoodsOrderActivity)
public class GroupPayGoodsOrderActivity extends BaseActivity<GroupPayGoodsViewModel, ActivityGroupPayGoodsOrderBinding> {
    @Autowired(name = RouterKey.NO, desc = "货源No")
    public String no;
    //自定义字段列表
    private List<SingleItemEntity> mCustomList;
    private CargoCustomValueAdapter mCustomAdapter;
    //车辆选择
    private final List<CarInfo> mCarList = new ArrayList<>();
    String orderNo;
    private MixCarListPopWindow carListPopWindow;
    private CarInfo car;
    CompanyGoodsOrderEntity mEntity = new CompanyGoodsOrderEntity();
    GoodsSourceDetail goodsSourceDetail;
    private Calendar selectedDate = Calendar.getInstance();
    private TimePickerView timePickerinsurance;
    private InvoicingCompanyPopWindow mCompanyPop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        EventBus.getDefault().register(this);
    }

    @Override
    protected int layoutId() {
        return R.layout.activity_group_pay_goods_order;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(GroupPayGoodsViewModel.class);
    }

    @Override
    protected void init() {
        ARouter.getInstance().inject(this);
        mBinding.setOnClick(this);
        mBinding.includeTitle.titleView.setText("确认接单");
        mBinding.includeTitle.ivBack.setOnClickListener(v -> {
            finish();
        });
        mBinding.tvCargoOrdersProtocol.setText(Html.fromHtml("确认提交即表示您已阅读并同意"
                + "<font color='#5792FD'>《经营帮货物运输协议》</font>全部内容"));

        initData();
        initEvent();
    }

    private void initData() {

        mBinding.tvCompanyName.setText(UserOperating.getInstance().getTeamOrCompanyName());
        mBinding.tvPersonName.setText(UserOperating.getInstance().getUserRealName());
        mBinding.tvPhone.setText(UserOperating.getInstance().getPhone());
        //自定义字段列表
        mCustomList = new ArrayList<>();
        mCustomAdapter = new CargoCustomValueAdapter(mCustomList);
        mBinding.rvCargoOrdersField.setNestedScrollingEnabled(false);
        mBinding.rvCargoOrdersField.setLayoutManager(new LinearLayoutManager(this));
        DividerDecoration.builder(this)
                .colorRes(R.color.transparent)
                .size(10, TypedValue.COMPLEX_UNIT_DIP)
                .build()
                .addTo(mBinding.rvCargoOrdersField);
        mCustomAdapter.bindToRecyclerView(mBinding.rvCargoOrdersField);

        initPopup();
        mEntity.setGoodsSourceNo(no);
        //获取货源信息
        mViewModel.getGoodsDetail(this, no);
        //获取信息
        mViewModel.getCarInfo(this, no);
        //获取当前位置
        mViewModel.getCurrentLocation(this);

    }

    private void initEvent() {
        //自定义字段删除监听
        mCustomAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.iv_release_cargo_del) {
                mCustomList.remove(position);
                mCustomAdapter.notifyDataSetChanged();
                if (mCustomList.size() == 0) {
                    mBinding.rvCargoOrdersField.setVisibility(View.GONE);
                }
            }
        });
        mViewModel.soureDetail.observe(this, this::synGoodsInfo);
        mViewModel.ldCar.observe(this, carInfos -> {
            syncCarList(carInfos);
        });
        mViewModel.ldLocation.observe(this, this::syncLocation);
        mViewModel.ldCompanyInvoice.observe(this, entity -> {
            mCompanyPop.setData(entity);
            mCompanyPop.showDownPopwindow(mBinding.llInvoice, true);
            mCompanyPop.backgroundAlpha(0.5f);
        });

        mViewModel.ldTradeNo.observe(this, tradeNo -> {
            //接单成功后刷新货源详情
            EventBus.getDefault().post(LogisticsEvent.make().setMessageTag(EventConstant.EVENT_REFRESH_PAY_GOODS));
            //获取订单NO
            orderNo = tradeNo.getOrderNo();
            if (UserOperating.getInstance().isTeam()){
                UiUtil.sendMsg(EventConstant.EVENT_REFRESH_GOODS, tradeNo.getOrderNo());
            }
            if (NumberUtil.trim0(goodsSourceDetail.getMessagePrice()).equals("0")) {
                ActivityJump.jumpToActivity(this, TransportOrderDetailOwnerActivity.class, Pair.create("no", orderNo),
                        Pair.create("isGoodsOwner", TransportOrderDetailOwnerActivity.CAR_OWNER));
                finish();
                return;
            }
            if(UserOperating.getInstance().isCompany()) {
                new RoundDialog.Builder(this)
                        .title("提示")
                        .content("已为您创建待付订单，请联系公司财务至 我的 - 资金中心 - 待付订单支付信息费。支付时效30分钟")
                        .cancel("确定")
                        .singleBtn(true)
                        .cancelable(false)
                        .confirmCallback(call -> {
                            ActivityJump.jumpToActivity(this, TransportOrderDetailOwnerActivity.class, Pair.create("no", orderNo),
                                    Pair.create("isGoodsOwner", TransportOrderDetailOwnerActivity.CAR_OWNER));
                            finish();
                        })
                        .contentGravity(Gravity.CENTER)
                        .show();
            }else{
                PayInfoEntity paymentEntity = new PayInfoEntity();
                paymentEntity.amount = tradeNo.getAmount();
                paymentEntity.orderId = tradeNo.getFreightOrderNo();
                PersonPayActivity.start(this, tradeNo.getFreightOrderNo());
            }


        });
    }

    private void initPopup() {
        carListPopWindow = new MixCarListPopWindow(this);
        carListPopWindow.setSingleSelect(false);
        carListPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                List<CarInfo> carLists = (List<CarInfo>) key1;
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < carLists.size(); i++) {
                    CarInfo car = carLists.get(i);
                    sb.append(car.getNo());
                    if (carLists.size() != 1 && i != carLists.size() - 1) {
                        sb.append(",");
                    }
                    if (i == 0) {
                        mEntity.setCarNumber(car.getCarNumber());
                        mEntity.setHeightHurdle(car.getHeightHurdle());
                    }
                }
                mEntity.setCarNo(sb.toString());
                if(carLists.size()==0){
                    mBinding.tvCargoOrdersCar.setText("");
                } else if(carLists.size()==1) {
                    mBinding.tvCargoOrdersCar.setText("已选" + carLists.get(0).getCarNumber());
                }else{
                    mBinding.tvCargoOrdersCar.setText("已选" + carLists.get(0).getCarNumber() + "等" + carLists.size() + "辆车");
                }
            }
        });
        mCompanyPop = new InvoicingCompanyPopWindow(this);
        mCompanyPop.setOnResultClick((key1, key2, key3) -> {
            if (key1 == null) return;
            CompanyInvoiceEntity entity = (CompanyInvoiceEntity) key1;
            //设置公司信息
            mBinding.tvInvoiceCompany.setText(DefaultUtil.getString(entity.getCompanyName()));
            mEntity.setInvoiceInfoId(entity.getId() + "");
        });
    }

    /**
     * 同步定位信息
     */
    private void syncLocation(AMapAddressEntity entity) {
        if (entity == null) return;
        mBinding.tvCargoOrdersCarLocation.setText(String.format("%s%s%s",
                entity.getProvince(),
                entity.getCity(),
                entity.getDistrict()));
        mEntity.setLat(entity.getLatitude());
        mEntity.setLng(entity.getLongitude());
        mEntity.setProvinceName(entity.getProvince());
        mEntity.setCityName(entity.getCity());
        mEntity.setDistrictName(entity.getDistrict());
        mEntity.setProvinceNo(entity.getProvinceNo());
        mEntity.setCityNo(entity.getCityNo());
        mEntity.setDistrictNo(entity.getDistrictNo());
        mEntity.setDetailAddress(entity.getSnippet());
        mBinding.etCargoOrdersAddress.setVisibility(View.VISIBLE);
        mBinding.etCargoOrdersAddress.setText(DefaultUtil.getString(entity.getSnippet()));
    }

    public void synGoodsInfo(GoodsSourceDetail goodsSourceDetail) {
        this.goodsSourceDetail = goodsSourceDetail;
        mBinding.tvOwnerName.setText(goodsSourceDetail.getCompanyName());
        StringBuilder goodType = new StringBuilder();
        if (!TextUtils.isEmpty(goodsSourceDetail.getGoodsTypeName())) {
            goodType.append(goodsSourceDetail.getGoodsTypeName());
        }
        if (!TextUtils.isEmpty(goodsSourceDetail.getSecondGoodsTypeName())) {
            goodType.append(TextUtils.isEmpty(goodsSourceDetail.getGoodsTypeName()) ? goodsSourceDetail.getSecondGoodsTypeName() : "/" + goodsSourceDetail.getSecondGoodsTypeName());
        }
        mBinding.tvGoodsName.setText(goodType.toString());
        if (goodsSourceDetail.getFreightType() != null) {
            if (goodsSourceDetail.getFreightType() == 1) {
                mBinding.rlHint.setVisibility(View.VISIBLE);
                mBinding.llPhoneFreight.setVisibility(View.VISIBLE);
                mBinding.tvMoney.setText("电议");
            } else {
                mBinding.tvMoney.setText(NumberUtil.trim0(goodsSourceDetail.getFreight()) + goodsSourceDetail.getFreightUnitType());
            }
        }
        if (TextUtils.isEmpty(goodsSourceDetail.getWeight())) {
            if (!TextUtils.isEmpty(goodsSourceDetail.getVolume())) {
                mBinding.tvWeight.setText(NumberUtil.trim0(goodsSourceDetail.getVolume()) + "方");
            } else {
                mBinding.tvWeight.setText("/");
            }
        } else {
            mBinding.tvWeight.setText(NumberUtil.trim0(goodsSourceDetail.getWeight()) + "吨" + (TextUtils.isEmpty(goodsSourceDetail.getVolume()) ? "" : "  " + NumberUtil.trim0(goodsSourceDetail.getVolume()) + "方"));
        }
        mBinding.tvInvoice.setText(TextUtils.isEmpty(goodsSourceDetail.getInvoiceWords()) ? "/" : goodsSourceDetail.getInvoiceWords().equals("不开发票") ? goodsSourceDetail.getInvoiceWords() :
                NumberUtil.trim0(goodsSourceDetail.getTariff()) + "%" + goodsSourceDetail.getInvoiceWords());
        mBinding.tvLink.setText(String.format("%s/%s", goodsSourceDetail.getConnection(), goodsSourceDetail.getConnectionPhone()));
        mBinding.tvCargoOrdersPrice.setText(Html.fromHtml("需付信息费"
                + "<font color='#FF4B10'>" + NumberUtil.trim0(goodsSourceDetail.getMessagePrice()) + "</font>元"));
        //装货时间
        long currentTime = DateUtils.getCustomizeDayMorning(0, System.currentTimeMillis()).getTime();
        long beginTime = goodsSourceDetail.getShipmentTime();
        //装车时间
        if (CargoConstant.stampFormatLoadInput(goodsSourceDetail.getShipmentTime(), goodsSourceDetail.getStartPointTime()).equals(CargoConstant.stampFormatLoadInput(goodsSourceDetail.getShipmentEndTime(), goodsSourceDetail.getEndPointTime()))) {
            mBinding.tvGoodsTime.setText(CargoConstant.stampFormatLoadInput(goodsSourceDetail.getShipmentTime(), goodsSourceDetail.getStartPointTime()));
        } else {
            mBinding.tvGoodsTime.setText(CargoConstant.stampFormatLoadInput(goodsSourceDetail.getShipmentTime(), goodsSourceDetail.getStartPointTime()) + (TextUtils.isEmpty(CargoConstant.stampFormatLoadInput(goodsSourceDetail.getShipmentEndTime(), goodsSourceDetail.getEndPointTime())) ? "" : "-") + CargoConstant.stampFormatLoadInput(goodsSourceDetail.getShipmentEndTime(), goodsSourceDetail.getEndPointTime()));
        }
        //若当天日期在装货开始日期之后，则默认值为当天日期，否则，默认值为装货开始时间（日期）
        if (beginTime < currentTime) {
            mBinding.tvCargoOrdersTimes.setText(DateUtils.getDate());
            mEntity.setInTime(currentTime);
        } else {
            mBinding.tvCargoOrdersTimes.setText(DateUtils.timestampTo13DateNos(beginTime));
            mEntity.setInTime(beginTime);
        }

    }

    /**
     * 初始化车辆选择器
     */
    private void syncCarList(List<CarInfo> list) {
        mCarList.clear();
        if (list == null) return;
        mCarList.addAll(list);
        carListPopWindow.setData(list);
    }


    /**
     * 添加更多字段
     */
    private void addField() {
        if (mCustomList.size() >= 3) {
            MToast.showToast(this, "最多添加3个字段");
            return;
        }
        mCustomList.add(new SingleItemEntity());
        mCustomAdapter.notifyDataSetChanged();
        if (mBinding.rvCargoOrdersField.getVisibility() == View.GONE) {
            mBinding.rvCargoOrdersField.setVisibility(View.VISIBLE);
        }
    }


    private void setInsuranceTime() {
  /*      if (mEntity != null && mEntity.getInTime() != null) {
           // Date time = new Date(mEntity.getInTime());
            selectedDate.setTimeInMillis(mEntity.getInTime());
        }*/
        if (timePickerinsurance == null) {
            timePickerinsurance = new TimePickerBuilder(this, (date, v) -> {
                @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String format = sdf.format(date);
                mBinding.tvCargoOrdersTimes.setText(format);
                mEntity.setInTime(date.getTime());
            }).setType(new boolean[]{true, true, true, false, false, false}).setCancelText("取消").setSubCalSize(15)
                    .setRangDate(Calendar.getInstance(), null)
                    .setCancelColor(Color.parseColor("#666666"))
                    .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                    .setSubmitText("确定")
                    .setSubmitColor(Color.parseColor("#5792FD"))
                    .setTextColorCenter(Color.parseColor("#ff333333"))
                    .setContentTextSize(15)
                    .setLineSpacingMultiplier(2.5f)
                    .setDividerColor(Color.parseColor("#EDEDED"))
                    .setTitleText("选择到场时间")
                    .build();
        }
        timePickerinsurance.show();

    }

    @Override
    public void onClick(View v) {
        if (v == mBinding.tvCargoOrdersAdd) {
            addField();
        } else if (v == mBinding.llCargoOrdersCarLocation) {
            AMapDialog.launch(this);
        } else if (v == mBinding.tvCargoOrdersSubmit) {

            clearAllFocus();
            if (goodsSourceDetail.getFreightType() != null && goodsSourceDetail.getFreightType() == 1) {
                if (TextUtils.isEmpty(mBinding.tvFreight.getText().toString())) {
                    MToast.showToast(this, "请填写运费");
                    return;
                }
                int freight = NumberUtil.convertToInt(mBinding.tvFreight.getText().toString());
                if (freight < 10 || freight > 50000) {
                    MToast.showToast(this, "请输入10-50000内运费");
                    return;
                }
                mEntity.setAllFreight(mBinding.tvFreight.getText().toString());
            }
            long selectTime = mEntity.getInTime();
            long endTime = goodsSourceDetail.getShipmentEndTime() == null ? 0 : goodsSourceDetail.getShipmentEndTime();

            /**
             * 货源装货最后时间指：
             * 1.开始和结束时间都存在，则等于结束时间的日期。
             * 2.仅存在开始时间，则等于开始时间的日期。
             */
//            if (goodsSourceDetail.getShipmentTime() != null && goodsSourceDetail.getShipmentEndTime() == null) {
//                //计算是否是同一天
//                String biddingEndTime = DateUtils.stampToDay5(goodsSourceDetail.getShipmentTime());
//                String endTimes = DateUtils.stampToDay5(selectTime);
//                boolean isSameDay = !TextUtils.isEmpty(endTimes) && endTimes.equals(biddingEndTime);
//                //判断是否是同一天，同一天忽略截止时间判断
//                if (!isSameDay && selectTime > goodsSourceDetail.getShipmentTime()) {
//                    new RoundDialog.Builder(this)
//                            .title("提示")
//                            .content("当前货源最后可装货时间为" + CargoConstant.stampFormatLoadInput(goodsSourceDetail.getShipmentTime(), 0) + "，请重新选择预计到场时间")
//                            .cancel("确定")
//                            .singleBtn(true)
//                            .contentGravity(Gravity.CENTER)
//                            .show();
//                    return;
//                }
//
//            } else if (goodsSourceDetail.getShipmentTime() != null && goodsSourceDetail.getShipmentEndTime() != null) {
//
//                if (endTime != 0 && endTime < selectTime) {
//                    new RoundDialog.Builder(this)
//                            .title("提示")
//                            .content("当前货源最后可装货时间为" + CargoConstant.stampFormatLoadInput(goodsSourceDetail.getShipmentEndTime(), goodsSourceDetail.getEndPointTime()) + "，请重新选择预计到场时间")
//                            .cancel("确定")
//                            .singleBtn(true)
//                            .contentGravity(Gravity.CENTER)
//                            .show();
//                    return;
//                }
//            }
            String carInfo = mBinding.tvCargoOrdersCar.getText().toString();
            String location = mBinding.tvCargoOrdersCarLocation.getText().toString();
            String adress = mBinding.etCargoOrdersAddress.getText().toString();
            if (TextUtils.isEmpty(location)) {
                new RoundDialog.Builder(this)
                        .title("提示")
                        .content("请选所在地")
                        .cancel("暂不填写")
                        .singleBtn(true)
                        .contentGravity(Gravity.CENTER)
                        .show();
                return;
            }
            if (TextUtils.isEmpty(adress)) {
                new RoundDialog.Builder(this)
                        .title("提示")
                        .content("请输入楼牌号")
                        .cancel("暂不填写")
                        .singleBtn(true)
                        .contentGravity(Gravity.CENTER)
                        .show();
                return;
            }

            if (!mBinding.cbCargoOrdersProtocol.isChecked()) {
                MToast.showToast(this, "请先勾选运输协议");
                return;
            }
            mEntity.setDetailAddress(mBinding.etCargoOrdersAddress.getText().toString());
            //新增字段json
            if (mCustomList != null && mCustomList.size() > 0) {
                JsonObject field = new JsonObject();
                for (SingleItemEntity diy : mCustomList) {
                    field.addProperty(diy.getLeftString(), diy.getRightString());
                }
                mEntity.setAddField(field.toString());
            }
            if (!TextUtils.isEmpty(mBinding.etCargoQuotationMark.getText().toString())) {
                mEntity.setNote(mBinding.etCargoQuotationMark.getText().toString());
            }

            mViewModel.quotation(this, mEntity);

        } else if (v == mBinding.tvCargoOrdersProtocol) {
            EventBus.getDefault().postSticky(WebEvent.make(EventConstant.EVENT_WEBVIEW, UrlConfig.NEW_BASE_URL + "logistics/operate/html/file/transportAgreement"));
            WebActivity.start(this);
        } else if (v == mBinding.llCargoOrdersCar) {
            if (carListPopWindow != null) {
                carListPopWindow.showDownPopwindow(mBinding.llCargoOrdersCar, true);
                carListPopWindow.backgroundAlpha(0.5f);
            }
        } else if (v == mBinding.llCargoTimes) {
            setInsuranceTime();
        } else if (v == mBinding.llCargoCompany) {
            if (mViewModel.ldCompanyInvoice.getValue() == null) {
                mViewModel.getInvoiceList(this);
            } else {
                mCompanyPop.showDownPopwindow(mBinding.llInvoice, true);
                mCompanyPop.backgroundAlpha(0.5f);
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReFresh(ZMessageEvent event) {
        if (event.code == Constants.EVENT_REFRESH) {//放弃支付运费关闭
            finish();
        } else if (event.code == Constants.EVENT_REFRESH_ORDER) {//跳转订单详情
            ActivityJump.jumpToActivity(this, TransportOrderDetailOwnerActivity.class, Pair.create("no", orderNo),
                    Pair.create("isGoodsOwner", TransportOrderDetailOwnerActivity.CAR_OWNER));
            finish();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        if (requestCode == RequestCode.CODE_MAP) {
            AMapAddressEntity entity = AMapDialog.get(data);
            if (entity != null) {
                mBinding.tvCargoOrdersCarLocation.setText(String.format("%s%s%s",
                        entity.getProvince(),
                        entity.getCity(),
                        entity.getDistrict()));
                mBinding.etCargoOrdersAddress.setText(DefaultUtil.getString(entity.getSnippet()));
                //设置数据
                mEntity.setLat(entity.getLatitude());
                mEntity.setLng(entity.getLongitude());
                mEntity.setProvinceName(entity.getProvince());
                mEntity.setCityName(entity.getCity());
                mEntity.setDistrictName(entity.getDistrict());
                mEntity.setProvinceNo(entity.getProvinceNo());
                mEntity.setCityNo(entity.getCityNo());
                mEntity.setDistrictNo(entity.getDistrictNo());
                mEntity.setDetailAddress(entity.getSnippet());
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}